/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import FileManager.FileTransfer_CLIENT;
import FileManager.folderTree;
import Message.Message;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Vector;
import javax.swing.ImageIcon;

/**
 *
 * @author DucThien
 */
public class GUI_Main extends javax.swing.JFrame {

     public Thread threadRecieve;
     public Thread threadSend;	
     public static Socket clientsocket;
     public static FileTransfer_CLIENT fileManager = new FileTransfer_CLIENT();
     ///function
     
      public static ImageIcon createImageIcon(String path) {
          java.net.URL imgURL = GUI_Main.class.getResource(path);
          if (imgURL != null) {
              return new ImageIcon(imgURL);
          } else {
              System.err.println("Couldn't find file: " + path);
              return null;
          }
      }
      
      
      public static void RececieveData(Socket ss)
    {
            try	{				
                    ReciveServer sserver = new ReciveServer(ss);					
            }catch(Exception e)		{
                    System.out.println("There're some error");
            }	
    }
    
    
    /*congtt - Functions hand message from server*/
     public static void HandMessage(Message ms , Socket ss) throws IOException, AWTException{
            
            int type;
            type = ms.GetType();
            switch(type){
                case 1: // chat
                    HandChat(ms);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    HandViewDesktop(ms, ss);
                    break;
                case 5:
                    HandRemote(ms , ss);
                    break;
                case 6:
                    HandFile(ms);
                    break;
                case 7:
                    break;
                case 8:
                    break;
                case 9:
                    break;
                    
            }
            
        }
        
        public static void  HandChat(Message ms){
            String str = ms.GetData().toString();
            System.out.println("Server: " + str);
        }
        
        public static void HandFile(Message ms) throws IOException{
            int opt = ms.GetOption();
            Vector<folderTree> listFolderTree = null ;
            Message msSendForServer = null;
            ObjectOutputStream out = null;
            switch(opt){
                case 1 :
                    listFolderTree =  fileManager.getListFolderAndFiles(".");
                    msSendForServer = new Message(6,1,listFolderTree);
                    out = new ObjectOutputStream(clientsocket.getOutputStream());                         
                    out.writeObject(msSendForServer);
                    break;
                case 2 :
                    listFolderTree =  fileManager.getListFolderAndFiles("folder");
                    msSendForServer = new Message(6,1,listFolderTree);
                    out = new ObjectOutputStream(clientsocket.getOutputStream());                         
                    out.writeObject(msSendForServer);
                    break;             
            }
        }
        
        public static void HandRemote(Message ms , Socket ss) throws IOException, AWTException{
            int option = ms.GetOption();
            
            switch(option){
                case 1:
                    System.out.println("server yeu cau view desktop!!!");
                    CreateAndSendDataToServerViewDesktop(ss , 1);
                    break;
                case 2:
                    break;
                default:
                    break;
                            
            }
        }
          
        public static void HandViewDesktop(Message ms , Socket socket) throws IOException, AWTException{
            CreateAndSendDataToServerViewDesktop(socket, 2);
        }
            
        public static void HandShell(Message ms){
            
        }      
         /*end congtt - Functions hand message from server*/
        /*function for send data remote to server */
        
        public static void CreateAndSendDataToServerViewDesktop(Socket ss , int type) throws IOException, AWTException{
            System.out.println("Zo ham create and send data view sesktop");                   
            
            Robot robot = null; //Used to capture the screen
            Rectangle rectangle = null; //Used to represent screen dimensions

            GraphicsEnvironment gEnv=GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gDev=gEnv.getDefaultScreenDevice();

            //Get screen dimensions
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            rectangle = new Rectangle(dim);

            //Prepare Robot object
            robot = new Robot(gDev);                   
                    
           
            
            if(type == 1){
                
                System.out.println("Zo ham server deleagre");
                new ScreenSpyer(ss,robot,rectangle,1);
                new ServerDelegate(ss,robot);
            }
            else
            {
                System.out.println("Zo ham server chi view thoi");
                new ScreenSpyer(ss,robot,rectangle,0);               
            }
            //SendDesktop sd = new SendDesktop(ss,robot , rectangle);
             
            
            
            
            /*int i = 0;
             Robot robot = null; //Used to capture the screen
            Rectangle rectangle = null; //Used to represent screen dimensions

            GraphicsEnvironment gEnv=GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gDev=gEnv.getDefaultScreenDevice();

            //Get screen dimensions
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            rectangle = new Rectangle(dim);

            //Prepare Robot object
            robot = new Robot(gDev);
                 
                    
                 
            while( i <= 100)
            {
                try
                {
                   

                    BufferedImage image = robot.createScreenCapture(rectangle);
                 
                    ImageIcon imageIcon = new ImageIcon(image);

                    Object obj = new String("Hinh anh");    
                    
                    Message ms = new Message(5,2,imageIcon);
                     //Message ms = new Message(1,2,obj);
                    ObjectOutputStream out = new ObjectOutputStream(ss.getOutputStream());                          
                    System.out.println("Send lan thu: " + i+1);
                    out.writeObject(ms);
                    System.out.println("Send thanh cong lan thu: " + i+1);
                                    
                i++;
                }catch(Exception ex){
                    System.out.println("Loi send  " + ex.toString());                }
               
            }
            */
           
                /*
            
            for(int i = 1 ; i <= 10 ; i++){
                String img = "images/img_"+i+".jpg";
                 System.out.println("Start write image for server.");                 
                ImageIcon imgSend = createImageIcon(img);  
                Message ms = new Message(5,2,imgSend);
                ObjectOutputStream out = new ObjectOutputStream(ss.getOutputStream());                          

                out.writeObject(ms);
                System.out.println("write hinh to server cong.");  
                                    
            }*/
        }
        
        
        public static void Connect(String ip){
            
            try{			
                    Socket ss = new Socket(ip,3211); 
                    clientsocket = ss;
                    RececieveData(ss);// gọi thread để lúc nào cũng nhận data từ server

                     System.out.println("Start write."); 
                    Object obj = new String("abc client: ");
                    Message ms = new Message(1,2,obj); 
                    ObjectOutputStream out = new ObjectOutputStream(ss.getOutputStream());                         

                    out.writeObject(ms);
                    System.out.println("write thanh cong."); 
		}
		catch(Exception e)
                {
                    System.out.println("Error in fuinction Main client !");
                    System.out.println(e.toString());
		}
            
        }
        
        
     
     //end function
    /**
     * Creates new form GUI_Main
     */
    public GUI_Main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel4 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        btnConnet = new javax.swing.JButton();
        btnDisconnect = new javax.swing.JButton();
        btnRequireHelp = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        textArea1 = new java.awt.TextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client");
        setResizable(false);

        jPanel4.setBackground(new java.awt.Color(164, 180, 255));

        jPanel1.setForeground(new java.awt.Color(51, 51, 255));
        jPanel1.setOpaque(false);
        java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT);
        flowLayout1.setAlignOnBaseline(true);
        jPanel1.setLayout(flowLayout1);

        jLabel1.setFont(new java.awt.Font("Cambria", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 0, 153));
        jLabel1.setText("Current State : ");
        jPanel1.add(jLabel1);

        jLabel2.setFont(new java.awt.Font("Cambria", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 153));
        jLabel2.setText("Connect / Disconnet to Server");
        jPanel1.add(jLabel2);

        jPanel2.setOpaque(false);
        jPanel2.setLayout(new java.awt.GridLayout(1, 4, 10, 0));

        btnConnet.setBackground(new java.awt.Color(27, 228, 108));
        btnConnet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/server_connect.png"))); // NOI18N
        btnConnet.setToolTipText("Connect to server");
        btnConnet.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnConnet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnetActionPerformed(evt);
            }
        });
        jPanel2.add(btnConnet);

        btnDisconnect.setBackground(new java.awt.Color(134, 118, 122));
        btnDisconnect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/disconnect.png"))); // NOI18N
        btnDisconnect.setToolTipText("Disconnect from server");
        btnDisconnect.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(btnDisconnect);

        btnRequireHelp.setBackground(new java.awt.Color(102, 153, 255));
        btnRequireHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/question1.png"))); // NOI18N
        btnRequireHelp.setToolTipText("Require Help From Server");
        btnRequireHelp.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(btnRequireHelp);

        btnClose.setBackground(new java.awt.Color(255, 255, 255));
        btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/shutdown(1).png"))); // NOI18N
        btnClose.setToolTipText("Disconnect and Close Programe");
        btnClose.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(btnClose);

        jPanel3.setOpaque(false);

        jTabbedPane1.setForeground(new java.awt.Color(0, 0, 204));
        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.LEFT);
        jTabbedPane1.addTab("History Chat", textArea1);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(

        ));
        jScrollPane1.setViewportView(jTable1);

        jTabbedPane1.addTab("Message Form Server", jScrollPane1);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 529, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 235, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 184, Short.MAX_VALUE))
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConnetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnetActionPerformed
        // TODO add your handling code here:
        System.out.println("Connect to server!!!");
        Connect("localhost");
        
    }//GEN-LAST:event_btnConnetActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new GUI_Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnConnet;
    private javax.swing.JButton btnDisconnect;
    private javax.swing.JButton btnRequireHelp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private java.awt.TextArea textArea1;
    // End of variables declaration//GEN-END:variables
}
